<?php

namespace app\api\controller;

use app\common\model\Order;
use app\common\model\Orders;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;
/**
 * 会员收益
 *
 * api-MemberBenefits
 *
 * @Apidoc\Title("会员收益")
 * @Apidoc\Group("api")
 */
class MemberBenefits extends Auth
{

    /**
     * @Apidoc\Title ("列表")
     * list
     */
    public function list(): \think\response\Json
    {
        $list_rows = input('list_rows', 10, 'intval');
        $data = \app\common\model\MemberBenefits::where('member_id', $this->request->uid)
            ->append(['customer_name', 'buy_money'])
            ->withAttr('customer_name', function($value, $data) {
                return \app\common\model\Member::where('id', $data['subordinate_id'])->value('name');
            })
            ->withAttr('buy_money', function($value, $data) {
                return Orders::where('id', $data['orders_id'])->value('total_amount');
            })
            ->withAttr('state', function ($value, $data){
                $map = [
                    0 => '已到账',
                    1 => '提现中',
                    2 => '已提现'
                ];
                return $map[$value];
            })
            ->order('id desc')->paginate($list_rows);
        return success('', $data);
    }

    /**
     *  @Apidoc\Title ("统计数据")
     * detail
     */
    public function detail()
    {
        // 本月开始和结束日期到月的最后一秒
        $currentMonthStart = strtotime(date('Y-m-01 00:00:00'));
        $currentMonthEnd = strtotime(date('Y-m-t 23:59:59'));
        $this_month = \app\common\model\MemberBenefits::where('member_id', $this->request->uid)
            ->where('create_time', 'between', [$currentMonthStart,$currentMonthEnd] )
            ->sum('money');

        // 上个月开始和结束日期到月的最后一秒
        $lastMonthStart = strtotime(date('Y-m-01', strtotime('-1 month')) . ' 00:00:00');
        $lastMonthEnd = strtotime(date('Y-m-t', strtotime('-1 month')) . ' 23:59:59');
        $last_month = \app\common\model\MemberBenefits::where('member_id', $this->request->uid)
            ->where('create_time', 'between', [$lastMonthStart,$lastMonthEnd] )
            ->sum('money');
        $all = \app\common\model\MemberBenefits::where('member_id', $this->request->uid)->sum('money');
        $un_used = \app\common\model\MemberBenefits::where('member_id', $this->request->uid)
            ->where('state', 0)
            ->sum('money');

        return success('', [
            'all' => $all,
            'valid' => $un_used,
            'now' => $this_month,
            'last' => $last_month
        ]);

    }
}
